let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
class Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/08财报/个股主力持仓/基金/`;
        this.encode = 'GBK'
        this.params = {
            pageIndex: 1,
            pageTotal: '',
            code: ''
        }

        this.codeList = [];
        this.codeIndex = 0;

        this.data = []

        this.dateList = [
            '2018-06-30',
            '2018-03-31',
            '2017-12-31',
            '2017-09-30',
            '2017-06-30',
            '2017-03-31',
            '2016-12-31',
            '2016-09-30',
            '2016-06-30',
            '2016-03-31',
            '2015-12-31',
            '2015-09-30',
            '2015-06-30',
            '2015-03-31',
            '2014-12-31'
        ]
        this.dateIndex = 0;
    }
    /**
     * 获取url
     */
    getUrl(date) {
        //http://data.eastmoney.com/zlsj/detail/600519.html
        return `http://data.eastmoney.com/zlsj/detail.aspx?type=ajax&st=2&sr=-1&p=${this.params.pageIndex}&ps=30&jsObj=yovImHKb&stat=0&code=${this.params.code}&date=${this.params.date}&rt=51117948`
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('36个股_主力持仓_基金Controller')
        await this.sleep(500)
        if (this.codeIndex < this.codeList.length) {
            this.params.code = this.codeList[this.codeIndex]
            //判断日期
            if (this.dateIndex < this.dateList.length) {
                this.params.date = this.dateList[this.dateIndex]
                if (this.params.pageTotal === '' || this.params.pageIndex <= this.params.pageTotal) {
                    console.log(JSON.stringify(this.params))
                    let result = await this.getData('', this.isCache)
                    result = this.axiosDataFormat(result.toString());
                    let pageDate = result.data || [];
                    this.params.pageTotal = result.pages;
                    this.data = [...this.data, ...pageDate]
                    this.params.pageIndex++;
                    this.params.dateIndex = this.dateIndex
                    await this.getHistory()
                } else {
                    this.writeCsv(this.data);
                    this.dateIndex++;
                    this.data = [];
                    this.params.pageTotal = ''
                    this.params.pageIndex = 1;
                }
            } else {
                this.dateIndex = 0;
                this.codeIndex++;
                this.params.pageIndex = 1;
                this.params.pageTotal = ''
            }
            await this.getHistory()
        }

    }
    getParams() {
        let content = fs.readFileSync(`d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/09字典/沪深股票列表/沪深股票列表_${new Date().format('yyyyMMdd')}.csv`)
        content.toString().split(/\n/).map(line => {
            if (line) {
                this.codeList.push(line.split(',')[1])
            }
        })
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        let result = null
        try {
            result = JSON.parse(data.replace(/^var\s\w+?\s*\=/, '').trim())
        } catch (err) {
            try {
                result = eval('(' + data.replace(/^var\s\w+?\s*\=/, '').trim() + ')')
            } catch (err) {
                if (data.indexOf('502 Bad Gateway') > -1) {
                    return []
                } else {
                    console.log(err)
                }

            }
        }
        return result
    }

    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        if (arr && arr.length) {
            try {
                fs.writeFileSync(path.join(this.baseSrc, `个股主力持仓_基金_${this.params.code}_${this.params.date.replace(/-/g, '')}_${new Date().format('yyyyMMdd')}.csv`), this.convertToCSV(arr, 'title'), 'UTF-8')
            } catch (err) {
                console.log(err)
            }


        }
    }

    async main(startDate = '2015-01-01', isCache = true) {
        this.isCache = isCache;
        console.log('--->36个股_主力持仓_基金Controller')
        this.getParams();
        await this.getHistory()
        this.writeCsv(this.data);
    }
}

let controller = new Controller()
module.exports = controller
